<?php
/**
 * 用户模块 工具类
 * 公共类
 *
 * @author    wangmx <wangmx@yunys.com.cn>
 * @copyright 2016 QuanZhouYunYiShang Inc.
 */
namespace App\Services\UserService;

use App\Services\ImgServices\ImgTool;
use App\Services\ProductsService\ProductTool;
use DB;
use Illuminate\Support\Facades\Mail;
use Log;
use \App\Services\Tool\ImageProcessor\ImagickTool as ImagickTool;



class UserTool
{
    protected $ProductsService;

    public function __construct(ProductTool $Product)
    {
        $this->Product = $Product;
    }

    /**
     * *******************************************
     * *******************************************
     * **************** 公共 Tool *****************
     * *******************************************
     * *******************************************
     */

    /**
     * 根据user_id获取用户基本信息(用户昵称 头像)
     */
    public function userInfoByid($user_id)
    {
        $userinfo = DB::table('users')
            ->where('user_id', $user_id)
            ->select('user_id', 'nick_name', 'avatar', 'original_avatar')->first();
        if ($userinfo == null) {
            $user_info = (object)array('user_id' => $user_id, 'nick_name' => '', 'avatar' => '', 'original_avatar' => '');
            return $user_info;
        }
        $user_info = self::checkHeader($userinfo);
        return $user_info;
    }

    /**
     * @param $user_id
     * 获取头像
     */
    public function headerimgByid($user_id)
    {
        $avatarImg = DB::table('users')
            ->where('user_id', $user_id)
            ->value('avatar');
        if (empty($avatarImg)) {
            $avatar = 'Default_avatar.png';
            $avatarImg = asset('images/' . $avatar);
            return $avatarImg;
        }
        $avatarImg = self::checkHeaderimg($avatarImg);
        return $avatarImg;
    }

    /**
     * @param $user_id
     * 获取昵称
     */
    public function nicknameByid($user_id)
    {
        $nick_name = DB::table('users')
            ->where('user_id', $user_id)
            ->value('nick_name');
        if ($nick_name == null) {
            $nick_name = '';
        }
        return $nick_name;
    }

    static function getPhoneAndName($user_id)
    {
        $info = DB::table('users')
            ->where('user_id', $user_id)
            ->select('phone', 'nick_name')
            ->first();
        if ($info == null) {
            $info = '';
        }
        return $info;
    }

    //认证用户更新作品数
    public function addCreateNumToAuthentication($user_id)
    {
        $user_type = DB::table('users')->where('user_id', $user_id)->value('user_type');
        if ($user_type == 1) {
            $create_num = DB::table('products')->where([
                'user_id' => $user_id,
                'is_shelves' => 1,
                'state' => 1,
            ])->count();
            DB::table('designer_authentications')->where('user_id', $user_id)->update(['product_num' => $create_num]);
        } else if ($user_type == 2) {
            $create_num = DB::table('products')->where([
                'user_id' => $user_id,
                'is_shelves' => 1,
                'state' => 1,
            ])->count();
            DB::table('brand_authentications')->where('user_id', $user_id)->update(['product_num' => $create_num]);
        }
    }

    /**
     * user_id组获取用户昵称头像
     */
    public function headerImgs($user_ids)
    {
        if (count($user_ids) != 0) {
            $userinfos = DB::table('users')
                ->whereIn('user_id', $user_ids)
                ->select('user_id', 'nick_name', 'avatar', 'original_avatar')->get()->toArray();
            $data = [];
            foreach ($userinfos as $userinfo) {
                $user_info = self::checkHeader($userinfo);
                $data[] = $user_info;
            }
            return $data;
        } else {
            return array();
        }
    }

    /**
     * 获取用户粉丝数
     */
    public function fansNum($user_id)
    {
        $fans_num = DB::table('follows')->where(['follow_user_id' => $user_id, 'state' => 1])->count();
        return $this->numFormat($fans_num);
    }

    /**
     * 获取用户关注数
     */
    public function followNum($user_id)
    {
        $follow_num = DB::table('follows')->where(['user_id' => $user_id, 'state' => 1])->count();
        return $follow_num;
    }

    /**
     * 判断用户是否存在
     */
    public function isUser($user_id)
    {
        $isUser = DB::table('users')->where(['user_id' => $user_id, 'state' => 1])->first();
        if ($isUser == null) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 获取默认收货地址
     */
    public function defaultAddress($user_id)
    {
        $defaultAddress = DB::table('addresses')
            ->where(['user_id' => $user_id, 'state' => 1, 'address_type' => 1])
            ->select('address_id', 'consignee', 'phone', 'country', 'city', 'address')
            ->first();
        if ($defaultAddress == null) {
            $defaultAddress = DB::table('addresses')
                ->where(['user_id' => $user_id, 'state' => 1])
                ->orderBy('created_at', 'desc')
                ->select('address_id', 'consignee', 'phone', 'country', 'city', 'address')
                ->first();
            if ($defaultAddress == null) {
                $defaultAddress = (Object)array();
            }
        }
        return $defaultAddress;
    }

    /**
     * 根据address_id获取收货地址信息
     */
    public function addressByID($address_id, $user_id)
    {
        $info = DB::table('addresses')->where(['address_id' => $address_id, 'user_id' => $user_id])
            ->select('address_id', 'consignee', 'phone', 'country', 'city', 'address', 'address_type')
            ->first();
        if ($info == null) {
            $arr = array('message' => '用户收货信息', 'result' => (Object)array(), 'state' => 'M00000');
            return $arr;
        } else {
            $arr = array('message' => '用户收货信息', 'result' => $info, 'state' => 'M00000');
            return $arr;
        }
    }

    /**
     * 获取用户类型
     */
    public function userType($user_id)
    {
        $user_type = DB::table('users')->where('user_id', $user_id)->value('user_type');
        return $user_type;
    }

    /**
     * 余额
     */
    public function getBalance($user_id)
    {
        $balance = DB::table('users')->where('user_id', $user_id)->value('balance');
        $total_revenue = DB::table('users')->where('user_id', $user_id)->value('total_revenue');
        if (ceil($balance) == $balance) {
            $balance = floatval($balance);
        }
        if (ceil($total_revenue) == $total_revenue) {
            $total_revenue = floatval($total_revenue);
        }
        $data = array('balance' => $balance, 'total_revenue' => $total_revenue);
        return $data;
    }

    /**
     * 增加总收益
     */
    public static function addTotalRevenue($user_id, $money)
    {
        $total_revenue = DB::table('users')->where('user_id', $user_id)->value('total_revenue');
        $new_total_revenue = $total_revenue + $money;
        DB::table('users')->where('user_id', $user_id)->update(['total_revenue' => $new_total_revenue]);
        return true;
    }

    /**
     * 余额操作
     */
    public static function changeBalance($user_id, $money)
    {
        $balance = DB::table('users')->where('user_id', $user_id)->value('balance');
        $new_total_revenue = $balance + ($money);
        DB::table('users')->where('user_id', $user_id)->update(['balance' => $new_total_revenue]);
        return true;
    }

    /**
     * 注册时间
     */
    public function registerTime($user_id)
    {
        $register_time = DB::table('users')->where('user_id', $user_id)->value('created_at');
        return $register_time;
    }

    /**
     * 获取职位
     */
    public function getjob($user_id, $type)
    {
        if ($user_id == null) {
            $job = '';
        } else if ($type == 1) {
            $job = DB::table('designer_authentications')->where('user_id', $user_id)->value('job');
        } else if ($type == 2) {
            $job = DB::table('brand_authentications')->where('user_id', $user_id)->value('job');
        } else {
            $job = '';
        }
        return $job;
    }

    /**
     * 获取设计师公司名
     */
    public function getcompany($user_id)
    {
        $company = DB::table('designer_authentications')->where('user_id', $user_id)->value('company');
        if ($company == null) {
            $company = '';
        }
        return $company;
    }

    /**
     * 作品详情 关注的人
     * 参数: 用户ID数组
     */
    public function follows($users, $current_user_id)
    {
        if ($users != null) {
            $lists = [];
            foreach ($users as $user) {
                $user_id = $user->user_id;
                $nick_name = self::nicknameByid($user_id);
                $avatarImg = self::headerimgByid($user_id);
                $create_num = $this->Product->getProductNumByUserID($user_id);
                $is_follow = $this->is_follow($current_user_id, $user_id);
                $fans_num = self::fansNum($user_id);
                $user->nick_name = $nick_name;
                $user->avatar = $avatarImg;
                $user->is_follow = $is_follow;
                $user->create_num = $this->numFormat($create_num);
                $user->fans_num = $this->numFormat($fans_num);
                $user->user_type = $this->userType($user_id);

                $lists[] = $user;
            }
            return $lists;
        } else {
            return array();
        }
    }

    /**
     * 手机号码正则判断
     */
    public function checkPhone($phone)
    {
        if (preg_match("/1[34578]{1}\d{9}$/", $phone)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 邮箱正则
     */
    public function checkEmail($email)
    {
        $pattern = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
        if (preg_match($pattern, $email)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 身份证正则判断
     */
    public function checkCardID($card_id)
    {
        if (strlen($card_id) != 18) {
            return false;
        }
        $set = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
        $ver = array('1', '0', 'x', '9', '8', '7', '6', '5', '4', '3', '2');
        $arr = str_split($card_id);
        $sum = 0;
        for ($i = 0; $i < 17; $i++) {
            if (!is_numeric($arr[$i])) {
                return false;
            }
            $sum += $arr[$i] * $set[$i];
        }
        $mod = $sum % 11;
        if (strcasecmp($ver[$mod], $arr[17]) != 0) {
            return false;
        }
        return true;
    }

    /**
     * 认证用户认证表更新作品数
     */
    public function addCraeteNum($user_id)
    {
        $user_type = DB::table('user_id', $user_id)->value('user_type');
        $num = $this->Product->getProductNumByUserID($user_id);
        if ($user_type == 1) {
            DB::table('designer_authentications')->where('user_id', $user_id)->update(['create_num' => $num]);
        } else if ($user_type == 2) {
            DB::table('brand_authentications')->where('user_id', $user_id)->update(['create_num' => $num]);
        }
    }

    /**
     * [is_follow 是否关注]
     * @param  [int]  $user_id        [当前用户ID]
     * @param  [int]  $follow_user_id [查询的用户ID]
     * @return boolean                 [是否关注]
     *
     */
    public function is_follow($user_id, $follow_user_id)
    {
        //当前用户 user_id  查询用户 follow_user_id
        $check = DB::table('follows')->where(
            [
                'user_id' => $user_id,
                'follow_user_id' => $follow_user_id,
                'state' => 1,
            ]
        )->first();
        if ($check == null) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 认证用户销量增加
     */
    public function AddSellNum($user_id, $sell_num)
    {
        $check1 = DB::table('designer_authentications')->where('user_id', $user_id)->first();
        $check2 = DB::table('brand_authentications')->where('user_id', $user_id)->first();
        if ($check1 != null) {
            $num = DB::table('designer_authentications')
                ->where('user_id', $user_id)->value('sales_num');
            DB::table('designer_authentications')
                ->where('user_id', $user_id)
                ->update(['sales_num' => $num + $sell_num]);
        } else if ($check2 != null) {
            $num = DB::table('brand_authentications')
                ->where('user_id', $user_id)->value('sales_num');
            DB::table('brand_authentications')
                ->where('user_id', $user_id)
                ->update(['sales_num' => $num + $sell_num]);
        }
        return 'sucess';
    }

    /**
     * [getAuthticationUser 获取认证用户]
     * @param  [int] $user_type [认证类型 ]
     * @return [array]          [认证用户信息数组]
     */
    public function getAuthticationUser($user_type)
    {
        switch ($user_type) {
            case 0:
                //$lists = DB::table('users')->select('user_id', 'nick_name', 'phone', 'user_type')->get()->toArray();
                $lists = DB::table('users')->select('user_id', 'nick_name', 'phone', 'user_type')->paginate(10);
                foreach ($lists as $list) {
                    $list->user_type_name = $this->changeTypeName($list->user_type);
                }
                return $lists;
                break;
            case 1:
                $lists = DB::table('users')->where('user_type', 1)->select('user_id', 'nick_name', 'phone', 'user_type')->paginate(10);
                foreach ($lists as $list) {
                    $list->user_type_name = $this->changeTypeName($list->user_type);
                }
                return $lists;
                break;
            case 2:
                $lists = DB::table('users')->where('user_type', 2)->select('user_id', 'nick_name', 'phone', 'user_type')->paginate(10);
                foreach ($lists as $list) {
                    $list->user_type_name = $this->changeTypeName($list->user_type);
                }
                return $lists;
                break;
        }
    }

    /**
     * [searchUser 搜索用户]
     * @param  [string]  $name      [搜索词]
     * @param  integer $user_type [搜索的用户类型 ]
     */
    public function searchUser($name, $user_type = 0)
    {
        if (empty($user_type)) {
            $lists = DB::table('users')
                ->where('nick_name', 'like', '%' . $name . '%')
                ->orWhere('phone', 'like', '%' . $name . '%')
                ->select('user_id', 'nick_name', 'phone', 'user_type')
                ->paginate(10);
        } else {
            $lists = DB::table('users')
                ->where([['nick_name', 'like', '%' . $name . '%'], ['user_type', '=', $user_type]])
                ->orWhere([['phone', 'like', '%' . $name . '%'], ['user_type', '=', $user_type]])
                ->select('user_id', 'nick_name', 'phone', 'user_type')
                ->paginate(10);
        }
        foreach ($lists as $list) {
            $list->user_type_name = $this->changeTypeName($list->user_type);
        }
        return $lists;
    }

    /**
     * @param $user_ids
     * @return mixed
     * 用户组 By user_id
     */
    public function userListByUserid($user_ids)
    {
        $lists = DB::table('users')
            ->whereIn('user_id', $user_ids)
            ->select('user_id', 'nick_name', 'phone', 'user_type')
            ->get()
            ->toArray();
        foreach ($lists as $list) {
            $list->user_type_name = $this->changeTypeName($list->user_type);
        }
        return $lists;
    }

    /**
     * @param $user_id
     * @return mixed
     * 用户 By user_id
     */
    public function userByUserid($user_id)
    {
        $userinfo = DB::table('users')
            ->where('user_id', $user_id)
            ->select('user_id', 'nick_name', 'phone', 'user_type')
            ->first();
        if (!empty($userinfo)) {
            $userinfo->user_type_name = $this->changeTypeName($userinfo->user_type);
        }
        return $userinfo;
    }

    /**
     * @param $user_type
     * @return string
     * 用户类型转译 int->string
     */
    public function changeTypeName($user_type)
    {
        switch ($user_type) {
            case 0:
                $name = '普通用户';
                return $name;
            case 1:
                $name = '设计师';
                return $name;
            case 2:
                $name = '品牌商';
                return $name;
        }
    }

    /**
     * 设置推荐
     */
    public function commend($authentication_type, $user_id)
    {
        if ($authentication_type == 1) {
            DB::table('designer_authentications')->where('user_id', $user_id)->update(
                [
                    'is_commend' => 1,
                    'commend_time' => time(),
                ]
            );
        } else if ($authentication_type == 2) {
            DB::table('brand_authentications')->where('user_id', $user_id)->update(
                [
                    'is_commend' => 1,
                    'commend_time' => time(),
                ]
            );
        }
        $result = array('message' => '', 'result' => (Object)array(), 'state' => 'M00000');
        return $result;
    }

    /**
     * 取消推荐
     */
    public function cancelCommend($authentication_type, $user_id)
    {
        if ($authentication_type == 1) {
            DB::table('designer_authentications')->where('user_id', $user_id)->update(
                [
                    'is_commend' => 0,
                    'commend_time' => 0,
                ]
            );
        } else if ($authentication_type == 2) {
            DB::table('brand_authentications')->where('user_id', $user_id)->update(
                [
                    'is_commend' => 0,
                    'commend_time' => 0,
                ]
            );
        }
        $result = array('message' => '', 'result' => (Object)array(), 'state' => 'M00000');
        return $result;
    }

    /**
     * @param $user_id
     * 获取认证用户手机号码 非认证不返回
     */
    static function getPhoneByUserid($user_id)
    {
        $userinfo = DB::table('users')->where('user_id', $user_id)->first();
        if ($userinfo->user_type != 0) {
            return $userinfo->phone;
        } else {
            return '';
        }
    }

    /**
     * *******************************************
     * *******************************************
     * ************* UserService Tool **************
     * *******************************************
     * *******************************************
     */

    /**
     * 判断头像是否需要拼接 传userinfo
     */
    public function checkHeader($userinfo)
    {
        $ImgTool = new ImgTool(new ImagickTool());
        if (!empty($userinfo->avatar)) {
            $path_avatarImg = $userinfo->avatar;
            $avatarImg = substr($path_avatarImg, 0, 4);
            if ($avatarImg != 'http' && $path_avatarImg != null) {
                $userinfo->avatar = $ImgTool->getImgUrlByImgPath($path_avatarImg);
            }
        } else {
            $avatar = 'Default_avatar.png';
            $userinfo->avatar = $ImgTool->getImgUrlByImgPath($avatar);
        }
        if (!empty($userinfo->original_avatar)) {
            $path_original_avatar = $userinfo->original_avatar;
            $avatarImg = substr($path_original_avatar, 0, 4);
            if ($avatarImg != 'http' && $path_original_avatar != null) {
                $userinfo->original_avatar = $ImgTool->getImgUrlByImgPath($path_original_avatar);
            }
        } else {
            $avatar = 'original_Default_avatar.png';
            $userinfo->original_avatar = $ImgTool->getImgUrlByImgPath($avatar);
        }
        return $userinfo;
    }

    /**
     * [checkCoverMap 检查封面图]
     * @param  [object] $userinfo [用户信息]
     * @return [object] $userinfo [用户信息]
     */
    public function checkCoverMap($userinfo)
    {
        $cover_map = $userinfo->cover_map;
        $cover_mapImg = substr($cover_map, 0, 4);
        $ImgTool = new ImgTool(new ImagickTool());
        if ($cover_mapImg != 'http' && !empty($cover_mapImg)) {
            $userinfo->cover_map = $ImgTool->getImgUrlByImgPath($cover_map);
        }
        if (empty($cover_mapImg) || $cover_mapImg == '') {
            $userinfo->cover_map = asset('images/default_cover_map.png');
        }
        return $userinfo;
    }

    /**
     * 判断头像是否需要拼接 传avatar
     */
    public function checkHeaderimg($avatar)
    {
        $avatarImg_substr = substr($avatar, 0, 4);
        $ImgTool = new ImgTool(new ImagickTool());
        if ($avatarImg_substr != 'http' && !empty($avatar)) {
            $avatarImg = $ImgTool->getImgUrlByImgPath($avatar);
            return $avatarImg;
        } else if ($avatarImg_substr == 'http' && !empty($avatar)) {
            return $avatar;
        } else if (empty($avatar)) {
            $avatar = 'Default_avatar.png';
            $avatarImg = $ImgTool->getImgUrlByImgPath($avatar);
            return $avatarImg;
        }
    }

    /**
     * 检查验证码
     */
    public function checkIdentifying($phone, $identifying)
    {
        $random = DB::table('identifyings')->where('phone', $phone)->value('identifying'); //验证码
        if ($random == null) {
            $result = array('message' => '请先获取验证码', 'result' => (object)array(), 'state' => 'M01001');
            return $result;
        }
        $time = time();
        $random_time = DB::table('identifyings')->where('phone', $phone)->value('created_at'); //获取验证码的时间
        //验证码超时
        if ($time - $random_time > 60) {
//1分钟
            DB::table('identifyings')->where('phone', $phone)->delete();
            $result = array('message' => '验证码已经过时了，重发一个', 'result' => (object)array(), 'state' => 'M01002');
            return $result;
        }
        //验证码不正确
        if ($identifying != $random) {
            $result = array('message' => '验证码不对哦~', 'result' => (object)array(), 'state' => 'M01003');
            return $result;
        } else {
            //验证码验证正确
            DB::table('identifyings')->where('phone', $phone)->delete();
            $result = array('message' => '成功', 'result' => (object)array(), 'state' => 'M00000');
            return $result;
        }
    }

    /**
     * 判断手机号是否注册
     * 0登录 1注册
     */
    public function Type($phone)
    {
        $check = DB::table('users')->where('phone', $phone)->first();
        if ($check != null) {
            return 1;
        } else if ($check == null) {
            return 0;
        }
    }

    /**
     * 第三方登录tool
     * type登录类型字段名 login_type数据库名
     */
    public function thirdPartyLoginTool($type, $DBtype, $unique_id, $nick_name, $avatar, $udid, $login_type)
    {
        $hasunique_id = DB::table($DBtype)->where('unique_id', $unique_id)->first();

        if ($hasunique_id == null) {
        //第三方 第一次登录平台
            DB::table($DBtype)->insert(
                [
                    'unique_id' => $unique_id,
                    'nick_name' => $this->filterEmoji($nick_name),
                    'avatar' => $avatar,
                    'state' => 0, //未绑定手机号
                    'created_at' => time(),
                    'updated_at' => time(),
                ]
            );
            $data = array('bindPhone' => 0, 'unique_id' => $unique_id, 'login_type' => $login_type);
            $result = array('message' => '请绑定手机号', 'result' => $data, 'state' => 'M00000');
            return $result;
        } else {
        //第三方 非第一次登录平台
            $bindState = $hasunique_id->state; //判断是否已绑定手机号
            if ($bindState == 1) {
                //已绑定 直接登录
                $bindID = $hasunique_id->id; //第三方unique_id对应的ID
                $userinfo = DB::table('users')->where($type, $bindID)->first();
                if ($userinfo == null) {
            //数据可能出错 直接将第三方登录账号置为未绑定 state= 0
                    DB::table($DBtype)->where(['unique_id' => $unique_id])->update(['state' => 0]);
                    $data = array('bindPhone' => 0, 'unique_id' => $unique_id, 'login_type' => $login_type);
                    $result = array('message' => '请绑定手机号', 'result' => $data, 'state' => 'M00000');
                    return $result;
                }
                $user_id = $userinfo->user_id;
                DB::table('users')->where($type, $bindID)->update(['udid' => $udid, 'udid_record_time' => time()]);
                self::recordUdid($user_id, $udid);
                self::updateToken($user_id);
                $userinfo = DB::table('users')->where($type, $bindID)->select('user_id', 'nick_name', 'avatar', 'original_avatar', 'user_type', 'phone')->first();
                $userinfo->bindPhone = 1;
                $userinfo->unique_id = $unique_id;
                $userinfo = self::checkHeader($userinfo);
                $result = array('message' => '登录成功', 'result' => $userinfo, 'state' => 'M00000');
                return $result;
            } else {
//未绑定 绑定手机
                $data = array('bindPhone' => 0, 'unique_id' => $unique_id, 'login_type' => $login_type);
                $result = array('message' => '请绑定手机号', 'result' => $data, 'state' => 'M00000');
                return $result;
            }
        }
    }

    /**
     * 第三方绑定手机号tool
     */
    public function bindPhoneTool($phone, $type, $DBtype, $login_type, $unique_id, $udid)
    {
        $thirdPartyInfo = DB::table($DBtype)->where('unique_id', $unique_id)->first();
        if($thirdPartyInfo == null){
            $result = array('message' => '请重新登录', 'result' => (Object)array(), 'state' => 'M01001');
            return $result;
        }
        $bindID = $thirdPartyInfo->id; //第三方unique_id对应的ID
        $nick_name = $thirdPartyInfo->nick_name;
        $avatar = $thirdPartyInfo->avatar;
        if(empty($avatar)){
            $avatar = 'Default_avatar.png';
        }
        $bindState = $thirdPartyInfo->state;
        if (!preg_match("/[\x{4e00}-\x{9fa5}\w]+$/u", $nick_name) ||
            preg_match("/(\\\u[ed][0-9a-f]{3})/i", json_encode($nick_name)) != 0
        ) {
            //不允许特殊字符  后一个正则为判断emoji表情 将手机号码作为昵称
            $nick_name = substr_replace($phone, '****', 3, 4);
        }
        $checkname = $this->checkCompanyName($nick_name);
        if ($checkname == true) {
            $nick_name = substr_replace($phone, '****', 3, 4);
        }
        if ($bindState == 1) {
            $result = array('message' => '该第三方账号已绑定平台账号', 'result' => (Object)array(), 'state' => 'M01001');
            return $result;
        }
        $hasPhone = DB::table('users')->where('phone', $phone)->first();
        $token = $this->getToken();
        if ($hasPhone == null) {
            $cover_map = 'default_cover_map.png';
            DB::table('users')->insert(
                [
                    'phone' => $phone,
                    'nick_name' => $nick_name,
                    'original_avatar' => $avatar,
                    'avatar' => $avatar,
                    'login_type' => $login_type,
                    $type => $bindID,
                    'cover_map' => $cover_map,
                    'udid' => $udid,
                    'udid_record_time' => time(),
                    'token' => $token,
                    'token_record_time' => time(),
                    'created_at' => time(),
                    'updated_at' => time(),
                ]
            );
            $user_id = DB::table('users')->where('phone', $phone)->value('user_id');
            $this->Product->createDefaultCollections($user_id); //创建默认作品集
        } else {
            DB::table('users')->where('phone', $phone)->update(
                [
                    $type => $bindID,
                    'udid' => $udid,
                    'token' => $token,
                    'token_record_time' => time(),
                    'updated_at' => time(),
                ]
            );
        }
        DB::table($DBtype)->where('unique_id', $unique_id)->update(['state' => 1, 'updated_at' => time()]);
        $userinfo = DB::table('users')->where('phone', $phone)->select('user_id', 'nick_name', 'avatar', 'original_avatar', 'user_type')->first();
        $userinfo = self::checkHeader($userinfo);
        $result = array('message' => '绑定成功', 'result' => $userinfo, 'state' => 'M00000');
        return $result;
    }

    /**
     * 平台绑定第三方
     */
    public function bindThirdPartyTool($user_id, $type, $DBtype, $unique_id, $nick_name, $avatar, $bind_type)
    {
        $checkBind = DB::table('users')->where(['user_id' => $user_id])->value($type);
        if ($checkBind != 0) {
            $result = array('message' => '该账号已绑定' . $type, 'result' => (Object)array(), 'state' => 'M01001');
            return $result;
        }
        $hasunique_id = DB::table($DBtype)->where('unique_id', $unique_id)->first();
        if ($hasunique_id != null) {
            $bindState = $hasunique_id->state;
            if ($bindState == 1) {
                $result = array('message' => '该第三方账号已绑定手机号', 'result' => (Object)array(), 'state' => 'M01001');
                return $result;
            }
        } else {
            DB::table($DBtype)->insert(
                [
                    'unique_id' => $unique_id,
                    'nick_name' => $nick_name,
                    'avatar' => $avatar,
                    'state' => 0,
                    'created_at' => time(),
                    'updated_at' => time(),
                ]
            );
        }
        $thirdInfo = DB::table($DBtype)->where('unique_id', $unique_id)->first();
        $bindID = $thirdInfo->id;
        DB::table('users')->where('user_id', $user_id)->update([$type => $bindID, 'updated_at' => time()]);
        DB::table($DBtype)->where('unique_id', $unique_id)->update(['state' => 1, 'updated_at' => time()]);
        $data = array('hasBind' => array($type => 1));
        $result = array('message' => '绑定成功', 'result' => $data, 'state' => 'M00000');
        return $result;
    }

    /**
     * 查询是否绑定第三方平台
     * wechat->1已绑定 qq->1已绑定 weibo->1已绑定
     */
    public function hasBind($user_id)
    {
        $bindWechat = DB::table('users')
            ->where('user_id', $user_id)->value('wechat');
        $bindQq = DB::table('users')
            ->where('user_id', $user_id)->value('qq');
        $bindWeibo = DB::table('users')
            ->where('user_id', $user_id)->value('weibo');
        if ($bindWechat != 0) {
            $wechat = 1;
        } else {
            $wechat = 0;
        }
        if ($bindQq != 0) {
            $qq = 1;
        } else {
            $qq = 0;
        }
        if ($bindWeibo != 0) {
            $weibo = 1;
        } else {
            $weibo = 0;
        }
        $data = array('wechat' => $wechat, 'qq' => $qq, 'weibo' => $weibo);
        return $data;
    }

    /**
     * 绑定操作发送验证码判断号码是否已绑定第三方
     */
    public function checkBindBySendCode($type, $phone)
    {
        $checkData = DB::table('users')->where('phone', $phone)->value($type);
        if ($checkData != 0) {
            return true;
        }
    }

    //获取首字母
    public function getFirstCharter($str)
    {
        if (empty($str)) {
            return 'Default';
        }
        $fchar = ord($str{0});
        if ($fchar >= ord('A') && $fchar <= ord('z')) {
            return strtoupper($str{0});
        }

        $s1 = iconv('utf-8', 'gb2312//TRANSLIT//IGNORE', $str);
        $s2 = iconv('gb2312', 'utf-8//TRANSLIT//IGNORE', $s1);
        $s = $s2 == $str ? $s1 : $str;
        $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
        if ($asc >= -20319 && $asc <= -20284) {
            return 'A';
        }

        if ($asc >= -20283 && $asc <= -19776) {
            return 'B';
        }

        if ($asc >= -19775 && $asc <= -19219) {
            return 'C';
        }

        if ($asc >= -19218 && $asc <= -18711) {
            return 'D';
        }

        if ($asc >= -18710 && $asc <= -18527) {
            return 'E';
        }

        if ($asc >= -18526 && $asc <= -18240) {
            return 'F';
        }

        if ($asc >= -18239 && $asc <= -17923) {
            return 'G';
        }

        if ($asc >= -17922 && $asc <= -17418) {
            return 'H';
        }

        if ($asc >= -17417 && $asc <= -16475) {
            return 'J';
        }

        if ($asc >= -16474 && $asc <= -16213) {
            return 'K';
        }

        if ($asc >= -16212 && $asc <= -15641) {
            return 'L';
        }

        if ($asc >= -15640 && $asc <= -15166) {
            return 'M';
        }

        if ($asc >= -15165 && $asc <= -14923) {
            return 'N';
        }

        if ($asc >= -14922 && $asc <= -14915) {
            return 'O';
        }

        if ($asc >= -14914 && $asc <= -14631) {
            return 'P';
        }

        if ($asc >= -14630 && $asc <= -14150) {
            return 'Q';
        }

        if ($asc >= -14149 && $asc <= -14091) {
            return 'R';
        }

        if ($asc >= -14090 && $asc <= -13319) {
            return 'S';
        }

        if ($asc >= -13318 && $asc <= -12839) {
            return 'T';
        }

        if ($asc >= -12838 && $asc <= -12557) {
            return 'W';
        }

        if ($asc >= -12556 && $asc <= -11848) {
            return 'X';
        }

        if ($asc >= -11847 && $asc <= -11056) {
            return 'Y';
        }

        if ($asc >= -11055 && $asc <= -10247) {
            return 'Z';
        }

//        $str_substr = substr($str, 0, 1);
        //        if (is_numeric($str_substr)) {
        //            return $str_substr;
        //        }
        return 'Default';
//        return '1';
    }

    /**
     * 记录UDID
     *
     */
    public function recordUdid($user_id, $udid)
    {
        if (strlen($udid) != 0 && !empty($user_id)) {
            $hasUdid = DB::table('user_udids')->where(['user_id' => $user_id, 'udid' => $udid])->first();
            if ($hasUdid == null) {
                DB::table('user_udids')->insert(
                    [
                        'user_id' => $user_id,
                        'udid' => $udid,
                        'login_time' => time(),
                        'created_at' => time(),
                        'updated_at' => time(),
                    ]
                );
            } else {
                DB::table('user_udids')->where(['user_id' => $user_id, 'udid' => $udid])->update(
                    [
                        'login_time' => time(),
                    ]
                );
            }
        }
    }

    /**
     * 获取认证信息 设计师
     */
    public function getAuthenticationToDesigner($user_id)
    {
        $designer = DB::table('designer_authentications')->where('user_id', $user_id)
            ->select('user_id', 'real_name', 'gender', 'company', 'job', 'card_id', 'phone', 'email', 'front_card_url',
                'back_card_url', 'create_img_url_1', 'create_img_url_2', 'create_img_url_3', 'message', 'state')->first();
        if ($designer != null) {
            $designer->front_card_url = asset('images/' . $designer->front_card_url);
            $designer->back_card_url = asset('images/' . $designer->back_card_url);
            $designer->create_img_url_1 = asset('images/' . $designer->create_img_url_1);
            $designer->create_img_url_2 = asset('images/' . $designer->create_img_url_2);
            $designer->create_img_url_3 = asset('images/' . $designer->create_img_url_3);
            $remaining_time = $this->remainingTime(1, $user_id);
            $designer->remaining_time = $remaining_time;
            if ($remaining_time == -1) {
                $designer->state = 4;
            }
            if ($designer->state == 0 || $designer->state == 3) {
                $timeOut = DB::table('authentication_time_outs')->where('id', 1)->value('time_out');
                $designer->message = '预计' . $this->n2c($timeOut) . '个工作日内完成审核';
            }
            if ($designer->state == 1) {
                $designer->message = '若要再次修改信息,需联系客服哦~';
            }
            return $designer;
        } else {
            return (Object)array();
        }
    }

    /**
     * 阿拉伯数字转汉字数字
     */
    public function n2c($x)
    {
        $arr_n = array("零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十");
        return $arr_n[$x];
    }

    /**
     * 获取认证信息 品牌
     */
    public function getAuthenticationToBrand($user_id)
    {
        $brand = DB::table('brand_authentications')->where('user_id', $user_id)
            ->select('user_id', 'company_name', 'company_abbreviation', 'manager_name',
                'job', 'card_id', 'phone', 'front_card_url', 'back_card_url', 'business_license_url',
                'business_letters_url', 'message', 'state')->first();
        if ($brand != null) {
            $brand->front_card_url = asset('images/' . $brand->front_card_url);
            $brand->back_card_url = asset('images/' . $brand->back_card_url);
            $brand->business_license_url = asset('images/' . $brand->business_license_url);
            $brand->business_letters_url = asset('images/' . $brand->business_letters_url);
            $remaining_time = $this->remainingTime(2, $user_id);
            $brand->remaining_time = $remaining_time;
            if ($remaining_time == -1) {
                $brand->state = 4;
            }
            if ($brand->state == 0 || $brand->state = 3) {
                $timeOut = DB::table('authentication_time_outs')->where('id', 1)->value('time_out');
                $brand->message = '预计' . $this->n2c($timeOut) . '个工作日内完成审核!';
            }
            if ($brand->state == 1) {
                $brand->message = '若要再次修改信息,需联系客服哦~';
            }
            return $brand;
        } else {
            return (Object)array();
        }
    }

    /**
     * 获取封面图
     */
    public function coverMap($user_id)
    {
        $cover_map = DB::table('users')->where('user_id', $user_id)->value('cover_map');
        if (!empty($cover_map) || $cover_map != '') {
            $coverImgUrl = asset('images/' . $cover_map);
        } else {
            $coverImgUrl = asset('images/default_cover_map.png');
        }
        return $coverImgUrl;
    }

    /**
     * 判断认证状态 品牌
     */
    public function checkAuthenticationToBrand($user_id)
    {
        $brand = DB::table('brand_authentications')->where('user_id', $user_id)->first();
        if ($brand == null) {
            return 3;
        } else {
            $state = $brand->state;
            if ($state == 0) {
                return 0;
            } else if ($state == 1) {
                return 1;
            } else if ($state == 2) {
                return 2;
            }
        }
    }

    /**
     * 判断认证状态 设计师
     */
    public function checkAuthenticationToDesigner($user_id)
    {
        $designer = DB::table('designer_authentications')->where('user_id', $user_id)->first();
        if ($designer == null) {
            return 3;
        } else {
            $state = $designer->state;
            if ($state == 0) {
                return 0;
            } else if ($state == 1) {
                return 1;
            } else if ($state == 2) {
                return 2;
            }
        }
    }

    /**
     *随机数函数,$length为随机的数字长度
     */
    public function getRandomString($len, $chars = null)
    {
        if (is_null($chars)) {
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        }
        mt_srand(10000000 * (double)microtime());
        for ($i = 0, $str = '', $lc = strlen($chars) - 1; $i < $len; $i++) {
            $str .= $chars[mt_rand(0, $lc)];
        }
        return $str;
    }

    /**
     * 生成token随机数
     */
    public function getToken()
    {
        $token = self::getRandomString(3) . '_' . self::getRandomString(6) . '_' . self::getRandomString(9);
        return $token;
    }

    /**
     * 更新token
     */
    public function updateToken($user_id)
    {
        $token = $this->getToken();
        if (!empty($user_id)) {
            DB::table('users')->where('user_id', $user_id)->update(
                [
                    'token' => $token,
                    'token_record_time' => time(),
                ]
            );
            return $token;
        }

    }

    //随机数函数,$length为随机的数字长度
    public function random($length)
    {
        $key = "";
        $pattern = '1234567890';
        for ($i = 0; $i < $length; $i++) {
            $key .= $pattern{mt_rand(0, 9)}; //生成php随机数
        }
        return $key;
    }

    /**
     * 身份证实名
     */
    public function VerifiedCard($real_name, $card_id)
    {
        $appkey = "c55e4130dcd41bc1bea4903af8e16523";
        $url = "http://op.juhe.cn/idcard/query";
        $params = array(
            "idcard" => $card_id, //身份证号码
            "realname" => $real_name, //真实姓名
            "key" => $appkey, //应用APPKEY(应用详细页查询)
        );
        $paramstring = http_build_query($params);
        $content = $this->juhecurl($url, $paramstring);
        $result = json_decode($content, true);
        if ($result) {
            if ($result['error_code'] == '0') {
                if ($result['result']['res'] == '1') {
//通过
                    $resultData = array('message' => '', 'result' => (Object)array(), 'state' => 'M00000');
                    return $resultData;
                } else {
//身份证号码和真实姓名不一致
                    $resultData = array('message' => '身份证号码和真实姓名不一致', 'result' => (Object)array(), 'state' => 'M00003');
                    return $resultData;
                }
            } else if (isset($result['resultcode'])) {
//当前可请求的次数不足
                if ($result['resultcode'] == '112') {
                    $this->SendToMail();
                    $resultData = array('message' => "系统忙,请稍后重试", 'result' => (Object)array(), 'state' => 'M00002');
                    return $resultData;
                }
            } else if ($result['error_code'] == 210304) {
                $resultData = array('message' => "不是一个合法的身份证号或姓名", 'result' => (Object)array(), 'state' => 'M00003');
                return $resultData;
            } else {
                $resultData = array('message' => "系统忙,请稍后重试", 'result' => (Object)array(), 'state' => 'M00001');
                return $resultData;
            }
        } else {
            $resultData = array('message' => "系统忙,请稍后重试", 'result' => (Object)array(), 'state' => 'M00001');
            return $resultData;
        }
    }

    public function VerifiedCardBack($real_name, $card_id)
    {
        $appkey = "c55e4130dcd41bc1bea4903af8e16523";
        $url = "http://op.juhe.cn/idcard/query";
        $params = array(
            "idcard" => $card_id, //身份证号码
            "realname" => $real_name, //真实姓名
            "key" => $appkey, //应用APPKEY(应用详细页查询)
        );
        $paramstring = http_build_query($params);
        $content = $this->juhecurl($url, $paramstring);
        $result = json_decode($content, true);
        $error_code = $result['error_code'];
        $substr_error_code = substr($error_code, 0, 1);
        if ($substr_error_code == '2') {
            $resultData = array('message' => "系统忙,请稍后重试", 'result' => (Object)array(), 'state' => 'M00005');
            return $resultData;
        }
        if ($result) {
            if ($result['error_code'] == '0') {
                if ($result['result']['res'] == '1') {
//通过
                    $resultData = array('message' => '', 'result' => (Object)array(), 'state' => 'M00000');
                    return $resultData;
                } else {
//身份证号码和真实姓名不一致
                    $resultData = array('message' => '身份证号码和真实姓名不一致', 'result' => (Object)array(), 'state' => 'M00003');
                    return $resultData;
                }
            } else if ($result['resultcode'] == '112') {
//当前可请求的次数不足
                $this->SendToMail();
                $resultData = array('message' => "系统忙,请稍后重试", 'result' => (Object)array(), 'state' => 'M00002');
                return $resultData;
            } else {
                $resultData = array('message' => "系统忙,请稍后重试", 'result' => (Object)array(), 'state' => 'M00004');
                return $resultData;
            }
        } else {
            $resultData = array('message' => "系统忙,请稍后重试", 'result' => (Object)array(), 'state' => 'M00005');
            return $resultData;
        }
    }

    /**
     * 发送邮件
     */
    public function SendToMail()
    {
        try {
            $data = ['email' => env('ORDER_RECE_EMAIL'),
                'full_name' => '',
                'order_id' => '',
                'tel' => '',
                'username' => '',
                'messages' => '身份证实名验证次数不足请充值,以免影响Mytee服务'];
            Mail::send('activemail', $data, function ($message) use ($data) {
                $message->to($data['email'], $data['username'])->subject($data['messages']);
            });
            return true;
        } catch (\Exception $e) {
            Log::info($e);
            return false;
        }
    }

    /**
     * 请求接口返回内容
     * @param  string $url [请求的URL地址]
     * @param  string $params [请求的参数]
     * @param  int $ipost [是否采用POST形式]
     * @return  string
     */
    public function juhecurl($url, $params = false, $ispost = 0)
    {
        $httpInfo = array();
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'JuheData');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            if ($params) {
                curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
            } else {
                curl_setopt($ch, CURLOPT_URL, $url);
            }
        }
        $response = curl_exec($ch);
        if ($response === false) {
            return false;
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        curl_close($ch);
        return $response;
    }

    /**
     * 获取认证剩余时间
     */
    public function remainingTime($type, $user_id)
    {
        if ($type == 1) {
            $info = DB::table('designer_authentications')->where('user_id', $user_id)->first();
            $timeOut = DB::table('authentication_time_outs')->where('id', 1)->value('time_out');
            if ($info->state == 0) {
                $create_at = $info->created_at;
                $remainingTime = $create_at + (86400 * $timeOut) - time();
                if ($remainingTime < 0) {
                    $remainingTime = -1;
                }
            } else {
                $remainingTime = 0;
            }
            return $remainingTime;
        } else if ($type == 2) {
            $info = DB::table('brand_authentications')->where('user_id', $user_id)->first();
            if ($info->state == 0) {
                $create_at = $info->created_at;
                $remainingTime = $create_at + (86400 * 3) - time();
                if ($remainingTime < 0) {
                    $remainingTime = -1;
                }
            } else {
                $remainingTime = 0;
            }
            return $remainingTime;
        }
    }

    //检验图片是否存在
    public function ValidImage($imgage)
    {
        $is_valid = ImgTool::imageUrlIsValid($imgage);
        if ($is_valid == false) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 数字格式化
     */
    public function numFormat($number)
    {
        if ($number < 999) {
            return $number;
        }
        if (1000 <= $number || 9999 > $number) {
            return round(($number / 1000), 1) . 'k';
        }
        if (10000 <= $number || 999999 > $number) {
            return round(($number / 10000), 1) . 'w';
        }
        if (1000000 <= $number || 9999999 > $number) {
            return round(($number / 100000), 1) . 'm';
        }
    }

    public function trimall($str) //删除空格

    {
        $qian = array(" ", "　", "\t", "\n", "\r");
        $hou = array("", "", "", "", "");
        return str_replace($qian, $hou, $str);
    }

    /**
     * 定时器
     * 检查第三方绑定情况
     */
    public static function checkThirdParty()
    {
        Log::info('-----检查第三方绑定-----');
        Log::info(date('Y年m月d日 h:i:s', time()));
        $wechats = DB::table('users')->where('wechat', '<>', 0)->select('wechat')->pluck('wechat')->toArray();
        $qqs = DB::table('users')->where('qq', '<>', 0)->select('qq')->pluck('qq')->toArray();
        $weibos = DB::table('users')->where('weibo', '<>', 0)->select('weibo')->pluck('weibo')->toArray();
        $wechatResult = DB::table('wechats')->whereNotIn('id', $wechats)->update(['state' => 0]);
        $qqResult = DB::table('qqs')->whereNotIn('id', $qqs)->update(['state' => 0]);
        $weiboResult = DB::table('weibos')->whereNotIn('id', $weibos)->update(['state' => 0]);
        $result = array('wechat' => $wechatResult, 'qq' => $qqResult, 'weibo' => $weiboResult);
        Log::info($result);
        return $result;
    }

    /**
     * 定时器
     * 清零身份认证错误次数
     */
    public static function cleanErrorNum()
    {
        $num = DB::table('card_error_nums')->update(['card_id_error_num' => 0]);
        Log::info('----清零身份认证错误次数----');
        Log::info($num);
        Log::info('-----------END-----------');
    }

    /**
     * 审核超时定时器
     */
    public static function updateTimeout()
    {
        $timeOut = DB::table('authentication_time_outs')->where('id', 1)->value('time_out');
        $timeOut = $timeOut * 3600;
        $designers = DB::table('designer_authentications')->where('state', 0)->get();
        $brands = DB::table('brand_authentications')->where('state', 0)->get();
        foreach ($designers as $designer) {
            $created_at = $designer->created_at;
            if (time() - $created_at > $timeOut) {
                DB::table('designer_authentications')->where('user_id', $designer->user_id)->update(
                    [
                        'state' => 2,
                        'message' => '审核超时~',
                        'updated_at' => time(),
                    ]
                );
            }
        }
        foreach ($brands as $brand) {
            $created_at = $brand->created_at;
            if (time() - $created_at > $timeOut) {
                DB::table('brand_authentications')->where('user_id', $brand->user_id)->update(
                    [
                        'state' => 2,
                        'message' => '审核超时~',
                        'updated_at' => time(),
                    ]
                );
            }
        }

    }

    /**
     * @param $name
     * @return bool
     * 检查昵称是否包含限制品牌名
     */
    public function checkCompanyName($name)
    {
        $name = strtolower($name);
        if ($name != '') {
            $lists = DB::table('company_name_limits')
                ->where('keyword', $name)
                ->select('keyword')
                ->get();
            foreach ($lists as $item) {
                $keyword = strtolower($item->keyword);
                if ($name == $keyword) {
                    return true;
                }
            }
        }
    }

    // 过滤掉emoji表情
    public function filterEmoji($str)
    {
        $str = preg_replace_callback(
            '/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str);

        return $str;
    }

    /**
     * 模糊搜索用户
     * @Author    zhouchao
     * @DateTime  2017-03-13
     * @copyright 2017 QuanZhouYunYiShang Inc.
     * @license   [license]
     * @version   [version]
     * @param     array
     * @param     integer 1 设计师 2 品牌商
     * @param     integer
     * @return    array
     */
    public function search_users($type, $keyword, $per_page=10)
    {
        $search_results = DB::table('users')
                            ->where('nick_name','like',$keyword.'%')
                            ->where('user_type',$type)
                            ->where('state',1)
                            ->select('nick_name','user_id','user_type','is_official')
                            ->paginate($per_page)
                            ->toArray();
        foreach($search_results['data'] as $user){
            $user->product_num = $this->Product->getProductNumByUserID($user->user_id);
            $user->fans_num = $this->fansNum($user->user_id);     
            $user->avatar = $this->headerimgByid($user->user_id);
        }
                    
        return $search_results;                   
         
    }

    /**
     * 根据关键字获取用户ID
     * @Author    zhouchao
     * @DateTime  2017-03-13
     * @copyright 2017 QuanZhouYunYiShang Inc.
     * @license   [license]
     * @version   [version]
     * @param     string
     * @return    array
     */
    public function search_user_ids($keyword)
    {
        $search_results = DB::table('users')
                            ->where('nick_name','like',$keyword.'%')
                            ->where('user_type','<>',0)
                            ->where('state',1)
                            ->pluck('user_id')
                            ->toArray();  
        return $search_results;
    }


}
